package com.sinosoft.ptas.control;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sinosoft.framework.core.api.domain.OrganizationEntity;
import com.sinosoft.framework.core.api.domain.RoleUserRefEntity;
import com.sinosoft.framework.core.api.domain.UserEntity;
import com.sinosoft.framework.core.api.service.OrganizationService;
import com.sinosoft.framework.core.api.service.RoleService;
import com.sinosoft.framework.core.api.service.UserService;
import com.sinosoft.framework.core.common.constants.ErrorConstants;
import com.sinosoft.framework.core.common.constants.UserConstants;
import com.sinosoft.framework.core.common.exception.BusinessException;
import com.sinosoft.framework.core.common.utils.FileUtils;
import com.sinosoft.framework.core.common.utils.StringUtil;
import com.sinosoft.framework.core.common.utils.ajax.ResponseData;
import com.sinosoft.ptas.control.dto.UserData;
/**
 * 用户管理
 * @author lianWuJun
 * @time   2017年2月23日 上午10:50:11
 */
@Controller
@RequestMapping(value = "user")
public class UserController {

	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	OrganizationService orgService;

	/**
	 * 新建用户
	 * @param userData 用户信息
	 * @return 用户传输类
	 */
	@RequestMapping(value = "/createUser.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData createUser(UserData userData) {
		try {
			String id = UUID.randomUUID().toString();
			userData.setId(id);
			userService.createUser(userData.toEntity());
			String uid = userData.getId();
			String[] rids = userData.getRids();
			RoleUserRefEntity roleUserRefEntity=new RoleUserRefEntity();//穿此实体类目的是为了接收切面的创建者创建时间
			roleService.createUserRoleRef(roleUserRefEntity,uid, rids);
			return new ResponseData(true, userData);
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), userData);
		}
	}

	/**
	 * 根据用户的编号删除用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteUser.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData deleteUser(String id) {
		try {
			userService.deleteUserById(id);
			return new ResponseData(true, UserConstants.DELETE_USER_SUCCESS);
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}

	/**
	 * 根据用户编号更新用户信息
	 * @param userData
	 * @return
	 */
	@RequestMapping(value = "/updateUser.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData updateUser(UserData userData) {
		try {
			userService.updateUser(userData.toEntity());
			String uid = userData.getId();
			String[] rids = userData.getRids();
			RoleUserRefEntity roleUserRefEntity=new RoleUserRefEntity();//穿此实体类目的是为了接收切面的创建者创建时间
			roleService.createUserRoleRef(roleUserRefEntity,uid, rids);
			return new ResponseData(true, UserConstants.UPDATE_USER_SUCCESS);
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}

	/**
	 * 根据用户的编号修改用户的状态
	 * @param id 人员id
	 * @param state人员状态
	 * @return http请求回执数据
	 */
	@RequestMapping(value = "/updateUserState.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData updateUserState(String id, String state) {
		try {
			userService.updateUserState(id, state);
			return new ResponseData(true, UserConstants.UPDATE_USERSTATE_SUCCESS);
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}

	/**
	 * 根据用户的实体属性查询用户
	 * @param userData  用户信息
	 * @return 用户传输类集合
	 */
	@RequestMapping(value = "/retrieveUsers.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData retrieveUsers(UserData userData) {
		try {
			List<UserEntity> userEntities = userService.retrieveUsers(userData.toEntity());
			List<UserData> userDatas = getUserDatas(userEntities);
			if (userDatas.size() > 0) {
				for (int i = 0; i < userDatas.size(); i++) {
					List<RoleUserRefEntity> roleUserRefEntities = roleService
							.retrieveRolesUserRefByUid(userDatas.get(i).getId());
					if (roleUserRefEntities.size() > 0) {
						String[] arr = new String[roleUserRefEntities.size()];
						for (int j = 0; j < roleUserRefEntities.size(); j++) {
							arr[j] = roleService.retrieveRoleById(roleUserRefEntities.get(j).getRid()).getId();
						}
						userDatas.get(i).setRids(arr);
					}
				}
			}
			ResponseData data = new ResponseData(true, userDatas);
			return data;
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}
	/*有图片的用户*/
	@RequestMapping(value = "/retrieveUsersImageFromDataBase.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData retrieveUsersImageFromDataBase(UserData userData) {
		try {
			List<UserEntity> userEntities = userService.retrieveUsers(userData.toEntity());
			List<UserData> userDatas = getUserDatas(userEntities);
			if (userDatas.size() > 0) {
				for (int i = 0; i < userDatas.size(); i++) {
					/*从数据库中显示图片*/
					if(userDatas.get(i).getPortrait()!=null){
						String image=FileUtils.byteArrayToBase64(userDatas.get(i).getPortrait());
						userDatas.get(i).setIconText(image);
					}
					List<RoleUserRefEntity> roleUserRefEntities = roleService
							.retrieveRolesUserRefByUid(userDatas.get(i).getId());
					if (roleUserRefEntities.size() > 0) {
						String[] arr = new String[roleUserRefEntities.size()];
						for (int j = 0; j < roleUserRefEntities.size(); j++) {
							arr[j] = roleService.retrieveRoleById(roleUserRefEntities.get(j).getRid()).getId();
						}
						userDatas.get(i).setRids(arr);
					}
				}
			}
			ResponseData data = new ResponseData(true, userDatas);
			return data;
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}

	/**
	 * 根据用户名查询用户 设置使用 回显使用
	 * @param userData 用户信息
	 * @return 用户实体
	 */
	@RequestMapping(value = "/retrieveUsersByUsername.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData retrieveUsersByUsername(UserData userData) {
		try {
			//userData.setId("564655b7-5476-441c-ad20-a2c0119c05b3");
			UserEntity userEntitie = userService.retrieveUserById(userData.getId());
			return new ResponseData(true, getUserData(userEntitie));
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}

	/*有图片的用户*/
	@RequestMapping(value = "/retrieveUsersByUsernameImageFromDataBase.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData retrieveUsersByUsernameImageFromDataBase(UserData userData) {
		try {
			UserEntity userEntitie = userService.retrieveUserById(userData.getId());
			if(userEntitie==null){
				return new ResponseData(false,  null);
			}
			if(userEntitie.getPortrait()!=null){
				String image=FileUtils.byteArrayToBase64(userEntitie.getPortrait());
				userEntitie.setIconText(image);
			}
			return new ResponseData(true, getUserData(userEntitie));
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}
	
	/**
	 * 根据用户名修改密码
	 * @param userData  用户信息
	 * @return http请求回执数据
	 */
	@RequestMapping(value = "/resetUserPasswordOldToNew.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData resetUserPasswordOldToNew(UserData userData) {
		try {
			userService.updatePassword(userData.getUsername(), userData.getNewpassword());
			return new ResponseData(true, UserConstants.UPDATE_USERPASSWORD_SUCCESS);
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}
	
	/**
	 * 根据用户名重置密码
	 * @param userData 用户信息
	 * @return http请求回执数据
	 */
	@RequestMapping(value = "/resetUserPassword.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData resetUserPassword(UserData userData) {
		try {
			userService.updatePassword(userData.getUsername(), UserConstants.USER_PASSWORD);
			return new ResponseData(true, UserConstants.UPDATE_USERPASSWORD_SUCCESS);
		} catch (BusinessException e) {
			return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
		}
	}

/**
 * 	验证旧密码
 * @param userData 用户信息
 * @return http请求回执数据
 */
	@RequestMapping(value = "/validateUserOldPasseord.service", method = RequestMethod.POST)
	@ResponseBody
	public  ResponseData validateUserOldPasseord(UserData userData) {
		try {
			if(userService.matchPassword(userData.getUsername(), userData.getPassword())){
				return new ResponseData(true, UserConstants.UPDATE_USERPASSWORD_SUCCESS);
			}else{
				return new ResponseData(false, UserConstants.ERROE_PASSWORD);	
			}
			
	} catch (BusinessException e) {
		return new ResponseData(false, e.getErrorCode(), e.getMessage(), null);
	}
	}

	/**
	 * 用户信息验证 是否重复 返回true 是，重复 返回false 不是，不重复
	 * 
	 * @param userData
	 *            用户信息
	 * @return http请求回执数据
	 */
	@RequestMapping(value = "/validateUserInfo.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData validateUserInfo(UserData userData) {
		try{
			userService.validateUserInfo(userData.toEntity());
			return new ResponseData(false, ErrorConstants.SUCCESS_CODE, ErrorConstants.SUCCESS_MESSAGE, null);
		} catch (BusinessException e) {
			return new ResponseData(true, e.getErrorCode(), e.getMessage(), null);
		}
	}
	
	/**
	 * 
	 * 根据rid查询用户，分为两类，根据flag,当flag为1，查询没有绑定此rid的用户，flag为0时反之。
	 * @param roleId
	 *            ：要查询的角色id
	 * @param flag
	 *            ：查询标识，
	 *            "1":查询此角色没有绑定的人员, "0"：查询此角色绑定的人员
	 * @return 用户集合
	 */
	@RequestMapping(value = "/GetUsersByRidAndFlag.service", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData GetUsersByRidAndFlag(String roleId, String flag) {
		if (StringUtil.isBlank(roleId) || StringUtil.isBlank(flag)) {
			return new ResponseData(false, UserConstants.USER_RID_FLAG_ISNULL);
		}
		List<UserEntity> userEnetityList = new ArrayList<UserEntity>();
		if (flag.equals("1")) {
			userEnetityList = userService.getNoRoleUserByRoleId(roleId);
		} else if (flag.equals("0")) {
			userEnetityList = userService.getUserByRoleId(roleId);
		} else {
			userEnetityList = userService.retrieveUsers(new UserEntity());
		}
		List<UserData> userDataList = this.getUserDatas(userEnetityList);
		List<OrganizationEntity> orgList = orgService.retrieveOrganizations(
				null, null);
		for (OrganizationEntity org : orgList) {
			userDataList.add(new UserData(org.getId(), org.getName(), null));
		}
		return new ResponseData(true, userDataList);
	}
	

	/**
	 * 实体类集合转化传输类集合
	 * 
	 * @param entitys
	 *            用户实体集合
	 * @return 用户传输集合
	 */
	private List<UserData> getUserDatas(List<UserEntity> entitys) {
		int size = entitys.size();
		List<UserData> UserDatas = new ArrayList<UserData>();
		for (int i = 0; i < size; i++) {
			UserData data = new UserData();
			data.toUserData(entitys.get(i));
			UserDatas.add(data);
		}
		return UserDatas;
	}

	/**
	 * 实体类转化传输类
	 * 
	 * @param entity
	 *            用户实体
	 * @return 用户传输
	 */
	private UserData getUserData(UserEntity entity) {
		UserData data = new UserData();
		data.toUserData(entity);
		return data;
	}
}